package com.ericsson.middleware.slsp;


import java.util.logging.Level;
import java.util.logging.Logger;

import org.apache.commons.httpclient.HttpStatus;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;

import com.ericsson.middleware.PropertiesProvider;
import com.ericsson.middleware.utils.JsonUtil;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;

public class SmartParkingClient {
	
	private final static Logger LOGGER = Logger
			.getLogger(SmartParkingClient.class.getName());
	
	public ParkingSpot[] getParkingSpots() {

		try {						
			Client client = Client.create();

			WebResource webResource = client.resource(PropertiesProvider.getPARKING_SPOTS_STATUS_PROVIDER_URL());

			ClientResponse response = webResource.type("application/json").get(
					ClientResponse.class);

			if (response.getStatus() != HttpStatus.SC_OK) {
				throw new RuntimeException("Failed : HTTP error code : "
						+ response.getStatus());
			}

			String responseJson = response.getEntity(String.class);
			
			
			ParkingSpot[] parkingSpot =  (ParkingSpot[]) JsonUtil.fromJson(responseJson, ParkingSpot[].class) ;
			
			// parameters to send to CB
			setAdditionalAttributes(responseJson, parkingSpot);

			return parkingSpot;

		} catch (Exception e) {
			LOGGER.log(Level.SEVERE, "Failed to get parking_spots status");
		}
		return null;
	}
	
	private void setAdditionalAttributes(String responseJson, ParkingSpot[] parkingSpot) throws JSONException{
		JSONArray jsonMainNode = new JSONArray(responseJson);
		// Process each JSON Node 
		int lengthJsonArr = jsonMainNode.length();
		for (int i = 0; i < lengthJsonArr; i++) {
			// Get Object for each JSON node
			JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);

			// Fetch node values
			for (String jsonParam : PropertiesProvider.getJSON_PARKINGSPOT_ATTRIBUTES()) {
				parkingSpot[i].setAdditionalProperty(jsonParam, jsonChildNode.optString(jsonParam).toString());
			}
		}
	}
}